package com.example.warehouse.controller;

import com.example.warehouse.entity.Product;
import com.example.warehouse.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = "http://localhost:63342")
@RestController
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductService productService;
    // 获取所有商品
    @GetMapping
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }

    // 根据ID获取商品
    @GetMapping("/{id}")
    public Product getProductById(@PathVariable Long id) {
        return productService.getProductById(id);
    }

    // 根据名称获取商品
    @GetMapping("/name/{name}")
    public Product getProductByName(@PathVariable String name) {
        return productService.getProductByName(name);
    }

    // 添加商品
    @PostMapping
    public String addProduct(@RequestBody Product product) {
        productService.addProduct(product);
        return "商品添加成功";
    }

    // 更新商品
    @PutMapping("/{id}")
    public String updateProduct(@PathVariable Long id, @RequestBody Product product) {
        product.setId(id);  // 设置ID以便更新
        productService.updateProduct(product);
        return "商品更新成功";
    }

    // 删除商品
    @DeleteMapping("/{id}")
    public String deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
        return "商品删除成功";
    }
}
